<template>
	<view class="container">
		<view class="header">
			<text class="title">镇北盲盒</text>
			<view class="zjCook" @click="toRecard()">
				查看中奖记录
			</view>
		</view>
		<view class="bg">
			<view class="title">
				一元夺宝
			</view>
			<view class="no-activity" v-if="!activity">
				目前一元夺宝暂无活动，请您敬请关注
			</view>
			<view class="cont" v-if="activity">
				<view class="rules">
					<text>参与本活动前，请用户详细阅读活动规则及相关条款。凡参与本活动，则视为用户已阅读、理解并同意活动规则全部内容。</text>
				</view>
				<view class="info">
					<view class="item">
						<p>
							<view class="circle">
							</view>活动时间
						</p>
						<text>{{ time.startTime }}至{{ time.endTime }}</text>
					</view>
					<view class="item">
						<p>
							<view class="circle">
							</view>活动规则
						</p>
						<text>{{ rule }}</text>
					</view>
					<view class="item" id="prize">
						<p>
							<view class="circle">
							</view>奖品展示
						</p>
						<view class="giftBox">
							<img v-for="(item, index) in selUserPrize" :src="item.thumb" alt="" />
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 		<view class="">
			{{showTime}} {{isUserSignedUp}} {{activity}}
		</view> -->
		<view class="button" :class="time.status == '0' || time.status == '2' ? 'disabledBtn' : ''"
			v-if="!showTime && isUserSignedUp && activity" @click="selUserBox()">
			<p v-if="time.status == '1'">{{ '立即报名' }}</p>
			<p v-if="time.status == '2'">{{ '已结束' }}</p>
			<p v-if="time.status == '0'">{{ "活动尚未开始" }}</p>
		</view>
		<view class="button" v-if="!isUserSignedUp && activity">
			<p>{{ countdown }}</p>
		</view>
		<view class="popupBox" v-if="showLottery && !isUnKown">
			<view class="title">
				恭喜获得
			</view>
			<view class="title">
				{{ lottery.prizeName }}
			</view>
			<image class="img" :src="lottery.picture" mode="aspectFill"></image>
			<view class="recard" @click="toReceive()">
				立即领取
			</view>
			<!-- 	<view v-if="showLottery" @click="hideDialog" class="close">
				<image src="../../static/center/return.png" mode=""></image>
			</view> -->
		</view>
		<view class="popupMask" v-if="showLottery"></view>
		<uni-popup ref="popup" type="bottom">
			<view class="pay">
				<h3>一元夺宝活动购买</h3>
				<view class="price">
					<text>单价：</text>
					<text>1镇北币</text>
				</view>
				<view class="button" @click="payment">
					确认购买
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import {
	$getStorage,
	$setStorage,
	$removeStorage
} from "@/utils/auth.js";
export default {
	data() {
		return {
			selUserPrize: [],
			time: null,
			remainingTimes: "", // 假设从后台获取到的剩余时间数据
			countdown: '', // 初始化倒计时字符串
			showTime: false,
			lottery: {}, //开奖结果
			showLottery: false,
			isUserSignedUp: false, // 标记用户是否已报名
			//未中奖显示
			// isUnKown:false,
			// content:""
			// 显示有无活动
			activity: false,
			// 规则
			rule: null,
			issueId: null
		};
	},
	computed: {
		userInfo() {
			return this.$store.getters.userInfo
		}
	},
	onLoad() {
		this.selectIssue();
		this.takePartIn();
		this.insert();
	},
	onShow() {
		console.log(this.countdown);
		this.$http('/snatchActivity/selectActivity', 'get').then(res => {
			if (res.code == 500) {
				this.activity = false
			} else {
				this.activity = true
				this.prizeDisplay()
				// this.insert()
				this.selectTake();
				this.snatchActivityRule();
			}
		});
		if ($getStorage("showLottery")) {
			this.showLottery = false;
		}
	},
	onHide() {
		// $removeStorage("showLottery")
	},
	onUnload() {
		// 在页面销毁前清除定时器，避免内存泄漏
		clearInterval(this.timer);
		// $removeStorage("showLottery")
	},
	methods: {
		// 查询期号id
		selectIssue() {
			this.$http('/snatchActivity/selectIssue', 'get').then(res => {
				this.issueId = res.data.id;
				$setStorage("issueId", this.issueId)
			})
		},
		// 用户参与一元夺宝
		takePartIn() {
			this.$http('/snatchActivity/takePartIn', 'post', {
				userId: this.userInfo.id,
				userName: this.userInfo.name,
				issueId: $getStorage("issueId")
			}).then(res => { })
		},
		startCountdown() {
			// 使用箭头函数确保定时器内部能够访问到组件实例的属性和方法
			let that = this
			this.timer = setInterval(() => {
				that.updateCountdown();
			}, 1000); // 每秒更新一次
		},
		updateCountdown() {
			// 使用正则表达式匹配剩余时间字符串中的数字部分
			const matchResult = this.remainingTimes.match(/\d+/g);
			if (matchResult && matchResult.length === 4) {
				let days = parseInt(matchResult[0]);
				let hours = parseInt(matchResult[1]);
				let minutes = parseInt(matchResult[2]);
				let seconds = parseInt(matchResult[3]);
				// 计算剩余总秒数
				let totalSeconds = days * 24 * 60 * 60 + hours * 60 * 60 + minutes * 60 + seconds;

				// 如果剩余时间大于0，则进行倒计时
				if (totalSeconds > 0) {
					// 减去1秒
					totalSeconds--;
					// 重新计算剩余天、小时、分钟和秒数
					days = Math.floor(totalSeconds / (24 * 60 * 60));
					hours = Math.floor((totalSeconds % (24 * 60 * 60)) / (60 * 60));
					minutes = Math.floor((totalSeconds % (60 * 60)) / 60);
					seconds = totalSeconds % 60; // 计算剩余秒数
					// 更新剩余时间
					this.remainingTimes = `${days}天 ${hours}时 ${minutes}分 ${seconds}秒`;
					// 更新倒计时字符串
					this.countdown = `${days}天 ${hours}时 ${minutes}分 ${seconds}秒`;
				} else {
					// 如果剩余时间小于等于0，清除定时器并提示倒计时结束
					clearInterval(this.timer);
					this.countdown = "已开奖";
					// this.showLottery = true
					this.remainingTime(); // 执行开奖操作	
				}
			} else {
				// 如果剩余时间格式不正确，输出错误信息到控制台
				// console.error("剩余时间格式不正确");
				// 将倒计时字符串置空，避免显示错误数据
				this.countdown = "已开奖";
				// 清除定时器，避免继续执行错误的倒计时逻辑
				clearInterval(this.timer);
			}
		},
		//活动规则
		async snatchActivityRule() {
			await this.$http('/snatchActivity/Rule', "get", {
				issueId: $getStorage("issueId")
			}).then(res => {
				this.rule = res.message
			})
		},
		// 活动开始时间
		async insert() {
			await this.$http('/snatchActivity/select', "get", {
				id: $getStorage("issueId")
			}).then(res => {
				if (res.code == 200) {
					this.time = res.data
					// this.selectTake();
					if (res.data.status != '2') {
						// this.activity = false
						$removeStorage("showLottery")
					}
				}
			})
		},
		// 报名状态
		selectTake() {
			// 判断是否参加了报名
			this.$http('/snatchActivity/selectTake', "get", {
				userId: this.userInfo.id
			}).then(res => {
				this.isUserSignedUp = res
				console.log(this.isUserSignedUp);
				if (!this.isUserSignedUp) {
					this.remainingTime();
				}
			})
		},
		// 奖品展示
		prizeDisplay() {
			this.$http('/snatchActivity/selUserPrize', "get", {
				issue: $getStorage("issueId")
			}).then(res => {
				if (res.code == 200) {
					this.selUserPrize = res.data
				}
			})
		},
		// 立即报名
		selUserBox() {
			if (this.time.status == '0') {
				return
			}
			if (this.time.status == '1') {
				this.$refs.popup.open('bottom')
			}


		},
		// 确定够买一元夺宝
		payment() {
			uni.showToast({
				title: "恭喜您购买成功",
				icon: "none"
			})
			this.$refs.popup.close();
			this.$http('/snatchActivity/selUserBox', "get", {
				userId: this.userInfo.id,
				issueId: this.issueId
			}).then(res => {
				if (res.code == 200) {
					uni.showToast({
						title: res.message,
						icon: "none"
					})
					// 获取剩余时间
					this.remainingTime();
				} else {
					uni.showToast({
						title: res.message,
						icon: "none"
					})
				}
			})
		},
		// 开奖时间
		async remainingTime() {
			console.log("startTime", this.time.startTime)
			await this.$http('/snatchActivity/remaining-time', "get", {
				startTime: this.time.startTime,
				userId: this.userInfo.id,
				issue: this.issueId
			}).then(res => {
				// 开奖的情况
				if (res.message == "活动已结束") {
					clearInterval(this.timer);
					if (this.time.status != '2') {
						this.winningRecord()
						// this.aLottery();

					} else {
						this.countdown = "已结束";
						this.winningRecord()
					}
				} else {
					// 未开奖的情况
					const decodedData = res.message
					this.remainingTimes = decodedData;
					this.showTime = true;
					this.isUserSignedUp = false;
					// 更新倒计时
					this.startCountdown();
				}
			})
		},
		// 倒计时结束之后抽奖
		// aLottery() {
		// 	this.$http('/snatchActivity/aLottery', "get", {
		// 		startTime: this.time.startTime,
		// 		issue: this.issueId
		// 	}).then(res => {
		// 		if (res.code == 200) {
		// 			this.winningRecord();
		// 		} else {
		// 			uni.showToast({
		// 				title: res.message,
		// 				icon: "none"
		// 			})
		// 		}
		// 	})
		// },
		// 开奖操作
		winningRecord() {
			this.$http('/snatchActivity/winningRecord', "get", {
				userId: this.userInfo.id,
				issueId: this.issueId
			}).then(res => {
				// 中奖的情况
				if (res.code == 200) {
					if (!$getStorage("showLottery")) {
						this.showLottery = true;
					}
					this.lottery = res.data
					this.countdown = "已开奖";
				} else {
					// 未中奖的情况
					clearInterval(this.timer);
					this.showLottery = false;
					// $setStorage("showLottery", false);
					this.countdown = "已结束";
					let that = this
					if (!$getStorage("showLottery")) {
						uni.showModal({
							title: '开奖结果',
							content: res.message,
							success: function (res) {
								if (res.confirm) {
									that.toReceive();
									// console.log('点击了确认')
									// $setStorage("showLottery", true);
								} else {
									console.log('点击了取消')
								}
							}
						})
					}
				}
			})
		},
		// 立即领取方法
		toReceive() {
			this.$http('/snatchActivity/UserClick', "get", {
				userId: this.userInfo.id,
				issueId: this.issueId
			}).then(res => {
				$setStorage("showLottery", true);
				this.showLottery = false;
				this.countdown = "已结束";
			})
		},
		hideDialog() {
			this.showLottery = false;
		},
		// 跳转中奖记录
		toRecard() {
			
			// if(this.time.status == 2 || this.countdown == "已开奖"){
			// if (this.countdown == "已结束" || this.countdown == "已开奖"){
				uni.navigateTo({
					url: "/pages/TreasureHunt/record"
				})
			// }
		}
	},
};
</script>



<style scoped lang="scss">
// 一元夺宝支付弹框
.pay {
	width: 100%;
	height: 300rpx;
	background-color: #fff;
	border-radius: 50rpx 50rpx 0 0;
	padding: 30rpx 0;

	h3 {
		margin: 30rpx 0 50rpx;
		text-align: center;
		color: #000;
	}

	.price {
		width: 100%;
		box-sizing: border-box;
		padding: 0 20rpx;
		display: flex;
		justify-content: space-between;
		color: #000;
		margin-bottom: 20rpx;
		font-weight: 100;

		text:nth-child(2) {
			font-weight: 900;
		}
	}

	.num {
		width: 100%;
		box-sizing: border-box;
		padding: 0 20rpx;
		display: flex;
		justify-content: space-between;
		color: #000;
		margin-bottom: 20rpx;
		font-weight: 100;
	}

	.button {
		width: 560rpx;
		height: 100rpx;
		line-height: 100rpx;
		margin: 30rpx auto;
		font-weight: 900;
		font-size: 35rpx;
		text-align: center;
		border-radius: 15rpx;
		color: #fff;
		background: url(../../static/seach.png) center/ cover no-repeat;
	}
}

.container {
	background: linear-gradient(rgb(26, 14, 66), rgb(9, 9, 24), rgb(33, 54, 67), rgb(9, 9, 24));
	width: 100%;
	height: 1600rpx;
}

.header {
	padding: 30rpx 0 60rpx;
	text-align: center;
	position: relative;

	.title {
		font-size: 39rpx;
		color: #fff;
	}

	.zjCook {
		position: absolute;
		color: #faff6b;
		right: 20rpx;
		top: 35rpx;
		text-decoration: underline;
		font-size: 25rpx;
	}
}

.cont {
	margin-top: -90rpx;
}

.circle {
	width: 20rpx;
	height: 20rpx;
	border-radius: 50%;
	background-color: #ff5500;
}

.no-activity {
	width: 380rpx;
	height: 130rpx;
	color: #fff;
	// line-height: 130rpx;
	text-align: center;
	margin: 0 auto;
	margin-top: 200rpx;
	background-color: rgba(0, 0, 0, 0.5);
	border-radius: 20rpx;
	padding: 60rpx 20rpx 20rpx 20rpx;
}

.bg {
	background-image: url('https://zzboomcos-1317756147.cos.ap-nanjing.myqcloud.com/blind-box/91151728730125701.png');
	background-size: cover;
	background-repeat: no-repeat;
	border-radius: 20rpx;
	margin: 30rpx auto 0;
	width: 85%;
	box-sizing: border-box;
	padding: 30rpx;
	height: 1200rpx;

	.title {
		background-image: url('../../static/green01.png');
		background-size: cover;
		background-repeat: no-repeat;
		width: 580rpx;
		height: 210rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: auto;
		font-weight: 900;
		color: #f3d26e;
		position: relative;
		top: -130rpx;
	}
}

.title {
	font-size: 35rpx;
	margin-bottom: 20rpx;
}

.rules {
	color: #fff;
	line-height: 24px;
	margin-bottom: 20px;
	font-size: 25rpx;
	word-wrap: break-word;
	word-break: break-all;
	text-indent: 2em;
	font-weight: 900;
}

.giftBox {
	display: flex;
	justify-content: space-between;
	flex-wrap: wrap;
	height: 200rpx;
	overflow-y: auto;

	// flex-start:start;
	img {
		width: 100rpx;
		height: 100rpx;
	}
}

.giftBox::after {
	display: 'block';
	content: "";
	width: 30%;
}


.info .item {
	margin-bottom: 10px;
	color: #fff;

	p {
		font-weight: 900;
		font-size: 30rpx;
		margin-bottom: 30rpx;
		display: flex;
		align-items: center;

		view {
			margin-right: 20rpx;
		}
	}
}

.info .item text {
	font-size: 25rpx;
	font-weight: 900;
	word-wrap: break-word;
	word-break: break-all;
}

#prize {
	margin-top: 70rpx;
}

.prizes {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
	margin-top: 20px;
}

.prize {
	width: 150px;
	height: 150px;
	border-radius: 8px;
	overflow: hidden;
	margin-bottom: 20px;
}

.button {
	background-image: url('../../static/radius.png');
	background-size: contain;
	background-repeat: no-repeat;
	width: 670rpx;
	height: 200rpx;
	margin: 0 auto;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: -170rpx;
	font-size: 30rpx;
	font-weight: 900;

	p {
		margin-top: -20rpx;
		color: #ff5500;
	}
}

.disabledBtn p {
	color: #999;
}

.prize image {
	width: 100%;
	height: 100%;
}

.btn {
	background-color: #f0ad4e;
	color: #fff;
	font-size: 18px;
	padding: 10px 20px;
	border-radius: 8px;
}

.popupMask {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	/* 半透明黑色遮罩层 */
	z-index: 99;
}

.close {
	width: 100%;
	height: 120rpx;
	text-align: center;
	line-height: 120rpx;
	margin-top: 190rpx;
}

.close image {
	width: 50rpx;
	height: 50rpx;
}

.popupBox {
	background-image: url('../../static/mask.png');
	width: 80%;
	height: 900rpx;
	background-size: contain;
	background-repeat: no-repeat;
	margin: 0 auto;
	z-index: 100;
	position: absolute;
	top: 200rpx;
	left: 10%;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-top: 30rpx;
	box-sizing: border-box;

	.img {
		width: 200rpx;
		height: 200rpx;
		margin-top: -70rpx;
	}

	.recard {
		width: 78%;
		height: 100rpx;
		background-color: #f7e4a5;
		color: #ff5500;
		font-weight: 900;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 10rpx;
		margin-top: 60rpx;
	}

	.title {
		font-size: 40rpx;
		font-weight: 900;
		color: #fff0ce;
		margin-bottom: 80rpx;
	}
}
</style>